package com.ljf.game.event;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.ljf.game.WebsocketManager;
import org.springframework.web.socket.WebSocketSession;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 描述 :
 *
 {
 "EVENT_CLASS":"EXIT_ROOM"
 }
 * <p>
 * 版本     作者     时间      内容
 * 1.0      lijinfeng       2025-04-29 14:32     create
 */
public class ExitRoomEvent extends AbstractEvent {

    public void run(WebSocketSession session,String text) {
        JSONObject jsonObject =  JSON.parseObject(text);
        String homeowner = jsonObject.get("HOME_OWNER").toString();

        ConcurrentHashMap<String, WebSocketSession> roomMap =  WebsocketManager.groupGet(homeowner);

        if(null == roomMap || roomMap.isEmpty()){
            WebsocketManager.sendMessage(session, new HashMap<>(), "房间 [" + homeowner + "] 不存在");
            return;
        }

        String username = WebsocketManager.getUsername(session);
        String message = username + " 退出房间";
        roomMap.remove(username);
        WebsocketManager.groupRemoveOne(homeowner,username);

        WebsocketManager.sendMessage(session,new HashMap<>(),message);

        HashMap<String, Object> hashMap = EventManager.getResultMap(text);

        // 房主退出
        if (username.equals(homeowner)){
            // 只有自己直接解散房间
            WebsocketManager.groupRemove(username);
            if (roomMap.isEmpty()){
                return;
            }

            // 设置新的房主
            for (Map.Entry<String, WebSocketSession> entry : roomMap.entrySet()) {
                hashMap.put("NEW_OWNER",entry.getKey());
                WebsocketManager.createGroup(entry.getKey(), entry.getValue());
                WebsocketManager.groupAdd(entry.getKey(),roomMap);
                break; // 可以正常跳出循环
            }
        }

        WebsocketManager.sendMessageToAll(roomMap ,hashMap, message);

    }
}
